package com.sunagy.demand.front.service.impl;

import com.sunagy.demand.front.dataobject.Product;
import com.sunagy.demand.front.dto.ProductDto;
import com.sunagy.demand.front.repository.ProductRepository;
import com.sunagy.demand.front.service.ProductService;
import com.sunagy.demand.front.utils.BeanUtil;
import com.sunagy.demand.front.utils.TreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * desc：#TODO fill me ！
 * author：三餘無夢生
 * date：2018/5/8
 * time：下午5:35
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;
    @Override
    public List<ProductDto> getTree() {
        List<Product> productList = productRepository.findAll();
        List<ProductDto> productDtoList = (List<ProductDto>) BeanUtil.copyPropertiesList(productList,ProductDto.class);
        productDtoList = TreeUtil.buildByRecursive(productDtoList,-1);
        return productDtoList;
    }

    @Override
    public List<ProductDto> getList() {
        List<Product> productList = productRepository.findAll();
        List<ProductDto> productDtoList = (List<ProductDto>) BeanUtil.copyPropertiesList(productList,ProductDto.class);
        return productDtoList;
    }

    @Override
    @Transactional
    public ProductDto add(Product product) {
        ProductDto productDto = new ProductDto();
        BeanUtils.copyProperties(productRepository.save(product),productDto);
        return productDto;
    }

    @Override
    @Transactional
    public ProductDto edit(Integer id, Product product) {
        ProductDto productDto = new ProductDto();
        Product p = productRepository.getOne(id);
        BeanUtil.copyProperties(p,product);
        BeanUtil.copyProperties(productDto,productRepository.save(p));
        return productDto;
    }

    @Override
    @Transactional
    public Integer del(Integer id) {
        productRepository.delete(id);
        return id;
    }

}
